package chinaums.plugin.quartz;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import chinaums.common.util.Results;
import chinaums.common.util.ResultsUrl;
import chinaums.common.util.ShortUrlUtil;
import chinaums.entity.Url;
import chinaums.service.IUrlService;
import chinaums.service.LongUrlLinkService;

import com.alibaba.fastjson.JSONObject;

/**
 * <p>Title:TransformErrorUrl</p>
 * <p>Description:转换错误的短链接</p>
 * @version v1.0
 * @author RenLei
 * 2017年7月21日
 */
@Component
public class TransformErrorUrl {
private static Logger log= LoggerFactory.getLogger(TransformErrorUrl.class);
@Autowired
private IUrlService urlService;
@Autowired
private LongUrlLinkService longService;
/**
 * 每隔一分钟执行一次该方法
 * 每一个小时执行一次 cron = 0 0 0/1 * * ? 
 * 0 53 * * * ?
 * 
 */
@Scheduled(cron = "0 0/5 * * * ?")
public void send(){
	try {
		//先执行修改长连接表的那些转换的失败的数据的version
		updateLongVersion();
		
		
		log.info("进入错误的短链接重新转换的定时任务!");
		//查询所有转换失败的短连接，重新取新浪接口去请求转换
		List<Url> urlList=urlService.selectErrorUrl();
		if(urlList==null||urlList.size()<=0){
			log.info("没有错误的短链接!");
			return;
		}
		log.info("错误的短链接集合数量是:"+urlList.size());
		//下面是分割数据的操作
		List<Url> newList=new ArrayList<Url>();
		//获取集合大小
		int otherList=urlList.size();
		//定义count数量
		int count=20;
		//定义循环次数
		int timeCount=0;
		//判断集合是否小于count,如果小于就只循环一次，count等于集合大小
		if(otherList<=count){//加一个！=0的判断
			count=otherList;
			timeCount=otherList/count;
		}else{
			if(otherList%count==0){
				timeCount=otherList/count;
			}else{
				timeCount=(otherList/count)+1;
			}
		}
		System.out.println("timeCount:"+timeCount);
		//把数据进行分页
		for(int i=0;i<timeCount;i++){
			if((i+1)==timeCount){
		        int startIndex = (i*count);
		        int endIndex = urlList.size();
		        newList =urlList.subList(startIndex,endIndex);
		    }else{
		        int startIndex = i*count;
		        int endIndex = (i+1)*count;
		        newList =urlList.subList(startIndex,endIndex);
		    }
			String newUrl1 = "";
			StringBuffer sbUrl= new StringBuffer();
			for (int j = 0; j < newList.size(); j++) {
				//用乐观锁控制多台服务器操作同一张表，避免数据重复
				Url url=new Url();
				url.setUrlid(newList.get(j).getUrlid());
				url.setVersion(newList.get(j).getVersion());
				int result=urlService.updateShortVersion(url);
				if(result==0){
					log.info("该错误的短链接，正在被其它服务器修改!");
					continue;
				}
				if(j!=0){
					//当不是第一个的时候拼接&url_long=字符
					newUrl1=sbUrl.append("&url_long="+newList.get(j).getLongurl()).toString();//将长连接地址加上&url_long=
						}else{
					newUrl1 = sbUrl.append(newList.get(j).getLongurl()).toString();
						}
			}
			String shortJson=ShortUrlUtil.getShortUrl(newUrl1);//获取短链接json
			//判断shortjson是否为空
			int k=0;
		    //当json为空时再次发送请求，如果超过十次没有返回成功，则跳出循环
			while(StringUtils.isBlank(shortJson)){
				if(k>10){
					log.info("超过10次依然没有请求成功");
					break;
				}
				shortJson=ShortUrlUtil.getShortUrl(newUrl1);
					k=k+1;
			}
			if(shortJson==null || "".equals(shortJson)){
				continue;
			}
			log.info("shortJson为:"+shortJson);
			//进行json解析，把相应的参数转换
			ResultsUrl ru = JSONObject.parseObject(shortJson, ResultsUrl.class);
			log.info("每次获取的短连接长度："+ru.getUrls().size());
			//获取urls字段的集合
			List<Results> rList = ru.getUrls();
			for(Results rs :rList){
				//修改短连接
				Url url=new Url();
				url.setLongurl(rs.getUrl_long());
				url.setShorturl(rs.getUrl_short());
				urlService.updateErrorUrl(url);
			}
			log.info("修改错误短链接成功");
		}
	} catch (Exception e) {
		log.info("修改错误短链接出错了");
		e.printStackTrace();
	}
}
public void updateLongVersion(){
	log.info("进入修改长连接的vesion的定时任务!");
	try {
			int result=longService.updateErrorVersion();
			if(result>0){
				log.info("修改长连接的vesion成功!");
			}else{
				log.info("不需要修改长连接的vesion!");
			}
	} catch (Exception e) {
		log.info("修改长连接的version定时任务出错了!");
		e.printStackTrace();
	}
}
}
